package top.cardone.security.shiro.web.filter.authc.impl;

import com.google.gson.Gson;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;
import top.cardone.context.ApplicationContextHolder;
import top.cardone.context.util.CodeExceptionUtils;
import top.cardone.security.shiro.authc.impl.OAuth2TokenImpl;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Writer;
import java.util.Map;

/**
 * Created by Administrator on 2016/2/4.
 */
@Log4j2
public class OAuth2FilterImpl extends AuthenticatingFilter {
	@Setter
	protected String credentialsParam = "token";

	@Setter
	protected String principalParam = "username";

	@Override
	protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest httpRequest = (HttpServletRequest) request;

		String accessToken = httpRequest.getHeader(credentialsParam);

		if (StringUtils.isBlank(accessToken)) {
			accessToken = request.getParameter(credentialsParam);
		}

		String principal = httpRequest.getHeader(principalParam);

		if (StringUtils.isBlank(principal)) {
			principal = request.getParameter(principalParam);
		}

		OAuth2TokenImpl oAuth2Token = new OAuth2TokenImpl();

		oAuth2Token.setCredentials(accessToken);

		oAuth2Token.setPrincipal(principal);

		return oAuth2Token;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		Subject subject = getSubject(request, response);

		if (!subject.isAuthenticated()) {
			return executeLogin(request, response);
		}

		return true;
	}

	@Override
	protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
		if (!StringUtils.startsWith(request.getContentType(), org.springframework.http.MediaType.APPLICATION_JSON_VALUE) && RequestMethod.GET.name().equalsIgnoreCase(((HttpServletRequest) request).getMethod())) {
			return super.onLoginFailure(token, e, request, response);
		}

		response.setCharacterEncoding(CharEncoding.UTF_8);
		response.setContentType(org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE);


		try (Writer out = response.getWriter()) {
			String requestURI = getPathWithinApplication(request);

			Map<String, String> errorInfo = CodeExceptionUtils.newMap(requestURI, e);

			errorInfo.put("errorCode", "000001");

			String json = ApplicationContextHolder.getBean(Gson.class).toJson(errorInfo);

			out.write(json);
		} catch (java.io.IOException ex) {
			log.error(ex.getMessage(), ex);
		}

		return false;
	}
}
